require 'socket'
require 'model_class'
require 'xml_parser'
require 'time'
require 'pause'
require 'timeout'

class MusicController < ApplicationController
	layout "standard-layout"
	def index
		list
		render :action => 'list'
	end

	def pause
		session["pause_info"].button_clicked()
		render :partial => "playing_controls"
	end

	def random
		clt = @session['client']
		if(clt.nil?)
			render_text ""
			return
		end
		name = clt.name
		sock = TCPSocket.new('localhost', 12346)
		sock.puts("<play client=\"#{name}\" random=\"random\"/>")
		node = nil
		recv = ""
		while node == nil
			begin
				recv += sock.recvfrom(1024).join()
				tmp = recv
				parser = XmlParser.new(tmp)
				node = parser.parse()
			rescue
				node = nil
			end
		end
		sock.close()

		# locate file...
		file = node["file"]
		@model = get_model()
		hash = @model.find_title_from_file(@session["client"], file)
		@current_title = hash["title"]
		@current_album = hash["album"]
		@current_artist = hash["artist"]
		@current_client = hash["client"]
		store_session()

		session['playing'] = true
		session['play_title'] = session['title']
		session['play_client'] = session['client']
		session['play_progress'] = 0
		session['play_start'] = Time.new
		session['pause_info'] = Pause.new(session['client'], 
						   'localhost', 12346)
		render :partial => "list"
	end

	def play
		title = session["title"]
		client = session["client"]
		if(title.nil? || client.nil?)
			return
		end

		begin
			t = TCPSocket.new('localhost', 12346)
			t.puts("<play client=\"#{client.name}\" 
				file=\"#{title.file}\"/>\n")
			session['playing'] = true
			session['play_title'] = session['title']
			session['play_client'] = session['client']
			session['play_progress'] = 0
			session['play_start'] = Time.new
			session['pause_info'] = Pause.new(session['client'], 
							   'localhost', 12346)
			t.close()
		rescue
			return
		end
		render :partial => "playing_controls"
	end

	def check_play
		if(session['playing'].nil? || !session['playing'] || 
		   session['play_title'].nil?)
			render :partial => "playing_controls"
			return
		end
		session['play_progress'] = (Time.new - 
			session['play_start'])
		session['play_progress'] -= session['pause_info'].pause_time
		session['play_progress'] = session['play_progress'].to_i
		if(session['play_progress'] >= 
		   session['play_title'].duration.to_i)
		   	sock = TCPSocket.new('localhost', 12346)
			clt = session['play_client'].name
			sock.puts("<pause client=\"#{clt}\"/>")
			sock.close()
			session['playing'] = false
		end
		render :partial => "playing_controls"
	end

	def list
		@model = get_model()
		logger.info @model
		if(@model == nil) 
			@current_client = nil
			@current_artist = nil
			@current_album = nil
			@current_title = nil
		else
			@current_client = session["client"]
			@current_artist = session["artist"]
			@current_album = session["album"]
			@current_title = session["title"]
		end
		if(!@params['client_id'].nil?)
			update_client(@params['client_id'])
			store_session()
			render :partial => 'list'
			return
		end
		if(!@params['artist_id'].nil?)
			update_artist(@params['artist_id'])
			store_session()
			render :partial => 'list'
			return
		end
		if(!@params['album_id'].nil?)
			update_album(@params['album_id'])
			store_session()
			render :partial => 'list'
			return
		end
		if(!@params['title_id'].nil?)
			update_title(@params['title_id'])
			store_session()
			render :partial => 'list'
			return
		end
		store_session()
	end
	
	def store_session()
		session["client"] = @current_client
		session["artist"] = @current_artist
		session["album"] = @current_album
		session["title"] = @current_title
	end

	def update_client(clt)
		if(@current_client.nil?)
			@current_client = @model.find_client(clt)
			@current_artist = nil
			@current_album = nil
			@current_title = nil
		elsif(@current_client.name == clt)
			return
		else
			@current_client = @model.find_client(clt)
			@current_artist = nil
			@current_album = nil
			@current_title = nil
		end
	end

	def update_artist(art)
		if(@current_client == nil)
			return
		end
		if(@current_artist.nil?)
			@current_artist = @current_client.artists[art]
			@current_album = nil
			@current_title = nil
		elsif(@current_artist.name == art)
			return
		else
			@current_artist = @current_client.artists[art]
			@current_album = nil
			@current_title = nil
		end
	end

	def update_album(alb)
		if(@current_artist == nil)
			return
		end
		if(@current_album.nil?)
			@current_album = @current_artist.albums[alb]
			@current_title = nil
		elsif(@current_album.name == alb)
			return
		else
			@current_album = @current_artist.albums[alb]
			@current_title = nil
		end
	end

	def update_title(t)
		if(@current_album == nil)
			return
		end
		if(@current_title.nil?)
			@current_title = @current_album.titles[t]
		elsif(@current_title.name == t)
			return
		else
			@current_title = @current_album.titles[t]
		end
	end

	def get_model()
		t = nil
		begin
			t = TCPSocket.new('localhost', 12346)
			t.puts("<list/>\n")
		rescue
			return
		end

		node = nil
		answer = "<model>"
		while node == nil
			begin
				timeout(11) do
					@buff = t.recvfrom(1024).join()
				end
				answer += @buff.gsub(/&/, '&amp;')
				tmp = answer + "</model>"
				parser = XmlParser.new(tmp)
				node = parser.parse()
			rescue TimeoutError
				return nil
			rescue
				node = nil
			end
		end
		t.close()
		puts "done"

		@model = ModelClass.instance()
		@model.parse(node)
		return @model
	end
end

